<template>
    <n-drawer :show="active" :width="width" :mask-closable="false" @update:show="(flag:boolean) => (active = flag)">
        <n-drawer-content  :native-scrollbar="false" title="重置人员绑定" closable>
            <n-space vertical :size="12">
                <n-alert title="提示" type="warning">您将对以下员工进行重置微信绑定操作</n-alert>
                <n-list bordered>
                    <n-list-item v-for="item in items">
                        <n-space>
                            <n-text code>{{ item.id }}</n-text>
                            <n-text>{{ item.name }}</n-text>
                        </n-space>
                    </n-list-item>
                </n-list>

                <n-divider />
                <n-form :model="model" :rules="rules" ref="formRef">
                    <n-grid :cols="24" :x-gap="24">
                        <n-form-item-gi :span="12" label="绑定密码" path="pwd" v-if="model.id">
                            <n-input placeholder="请填写绑定密码" v-model:value="model.pwd" maxlength="10" show-count clearable />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" label="有效时长（小时）" path="hour" v-if="model.id">
                            <n-input-number v-model:value="model.hour" :min="1" :max="24 * 7" clearable />
                        </n-form-item-gi>
                    </n-grid>
                </n-form>
            </n-space>
            <template #footer>
                <n-space justify="end">
                    <n-button type="tertiary" @click="() => (active = false)">
                        <template #icon>
                            <n-icon :component="CloseRound" />
                        </template>
                        关闭
                    </n-button>
                    <n-button type="warning" :loading="loading" @click="execSave">
                        <template #icon>
                            <n-icon :component="CheckRound" />
                        </template>
                        提交重置
                    </n-button>
                </n-space>
            </template>
        </n-drawer-content>
    </n-drawer>
</template>

<script lang="ts" setup>
import { computed, PropType, ref, onBeforeMount } from 'vue'
import { CloseRound, CheckRound } from '@vicons/material'

import { Http } from '@/libs'
import { useStore } from '@/store'
const store = useStore()
const width = computed(() => Math.max(store.state.browser.innerWidth * 0.4, 640))

const { $notification: notification } = window

const loading = ref(false)

const prop = defineProps({
    show: {
        type: Boolean,
        required: true,
    },
    items: {
        type: Array as PropType<any[]>,
        required: true,
    },
})

const emit = defineEmits(['update:show', 'refresh'])

const active = computed({
    get: () => prop.show,
    set: val => emit('update:show', val),
})

interface ModelType {
    id: string
    pwd: string
    hour: number
}

const formRef = ref<any>(null)

const model = ref<ModelType>({
    id: '',
    pwd: '',
    hour: 1,
})

const rules = {
    pwd: {
        required: true,
        trigger: ['blur', 'input'],
        validator(_rule: any, value: string) {
            if (!value) {
                return new Error('请填写绑定密码，4-10个字符，建议数字')
            } else if (Number(value) < 18) {
                return new Error('绑定密码长度为4-10个字符')
            }
            return true
        },
    },
    hour: {
        type: 'number',
        required: true,
        trigger: ['blur', 'input'],
        message: '请填写有效时长',
    },
}

const execReset = () => {
    model.value = {
        id: prop.items[0].id,
        pwd: '',
        hour: 1,
    }
}

const execSave = (e: Event) => {
    e.preventDefault()
    formRef.value.validate((errors: any[]) => {
        if (!errors) {
            loading.value = true
            Http.post('/ops/account/key/reset', model.value).then(resp => {
                if (resp.stat.err > 0) {
                    loading.value = false
                    return
                }
                emit('refresh', {})
                notification.success({
                    duration: 1500,
                    title: '操作成功',
                    content: '您已成功重置微信绑定',
                })
                setTimeout(() => {
                    loading.value = false
                    emit('update:show', false)
                }, 200)
            })
        } else {
            let msgs = errors.map(err => err[0].message)
            notification.error({
                duration: 1500,
                title: '请填写完整内容',
                description: '当前表单存在以下问题，请处理后提交',
                content: msgs.join('\n'),
            })
        }
    })
}

onBeforeMount(() => {
    execReset()
})
</script>
